package com.plian.system.service.yth.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.CollectionUtil;
import com.plian.system.entity.dp.AnnualWorkPlan;
import com.plian.system.entity.yth.stafffiles.WorkPlan;
import com.plian.system.mapper.yth.staffFiles.WorkPlanMapper;
import com.plian.system.service.yth.IWorkPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class WorkPlanServiceImpl extends ServiceImpl<WorkPlanMapper, WorkPlan> implements IWorkPlanService {

    private final String YTH_DATASOURCE_TYPE = "3";
    @Transactional(rollbackFor = Exception.class)
//    @DS("slave_1")
    @Override
    public List<AnnualWorkPlan> getAllProject(Date startTime, Date endTime) {
        List<AnnualWorkPlan> annualWorkPlans = new ArrayList<>();

        List<WorkPlan> workPlans = list(new LambdaQueryWrapper<WorkPlan>()
                .gt(Optional.ofNullable(startTime).isPresent(),WorkPlan::getCreateTime,startTime)
                .le(Optional.ofNullable(endTime).isPresent(),WorkPlan::getCreateTime,endTime)
        );
        if (CollectionUtil.isNotEmpty(workPlans)){
            annualWorkPlans = conversion(workPlans);
        }
        return annualWorkPlans;
    }
    private List<AnnualWorkPlan> conversion(List<WorkPlan> workPlans){
        List<AnnualWorkPlan> annualWorkPlans= new ArrayList<>();
        ZoneId zone = ZoneId.systemDefault();
        for (WorkPlan workPlan:workPlans){
            AnnualWorkPlan annualWorkPlan = new AnnualWorkPlan();
            annualWorkPlan.setCode(workPlan.getInvoiceCode());
            annualWorkPlan.setReportCompanyId(String.valueOf(workPlan.getReportOrgId()));
            Optional.ofNullable(workPlan.getReportTime()).ifPresent( m ->{
                annualWorkPlan.setReportTime(Date.from(m.atStartOfDay().atZone(zone).toInstant()));
            });
            annualWorkPlan.setDataSource(YTH_DATASOURCE_TYPE);
            annualWorkPlan.setDataSourceId(workPlan.getId().toString());
            annualWorkPlan.setAttachIds(workPlan.getFileIds());
            annualWorkPlan.setCreateCompanyId(workPlan.getCreateDept().toString());
            annualWorkPlan.setCreateUser(workPlan.getCreateUser().toString());
            annualWorkPlans.add(annualWorkPlan);
        }
        return annualWorkPlans;
    }
}
